package com.yjCar.controller;

import com.yjCar.pojo.User;
import com.yjCar.service.UserService;
import com.yjCar.utils.JwtUtils;
import com.yjCar.utils.RedisUtil;
import com.yjCar.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;
    @PostMapping("/login")
    public SysResult login(@RequestBody User user, HttpServletRequest request){
        User users = userService.login(user);

        //登录失败
        if(users == null || users.equals("null")){
            return SysResult.fail();
        }
        //其他数据以map集合存放在token中
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("email", user.getEmail());
        dataMap.put("status", user.getStatus());

        String token = jwtUtils.createJwt(users.getId().toString(), users.getUsername(),dataMap);
        redisUtil.setCacheObject("token", token);
        request.getSession().setAttribute("token", token);
        return SysResult.success(token);
    }

    @GetMapping("/logout")
    public SysResult logout(HttpSession session){
        //session.invalidate();
        redisUtil.deleteObject("token");
        return SysResult.success();
    }
}
